package com.mazaiting.screen.picture

import android.annotation.TargetApi
import android.app.Service
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.os.*
import android.util.Log
import android.view.View
import com.mazaiting.log.L
import com.mazaiting.screen.util.FileUtil
import com.mazaiting.screen.util.ScreenUtil
import com.mazaiting.widget.view.FloatView

/**
 * 截图服务
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class ScreenService : Service() {
    companion object {
        /**
         * 日志 Tag
         */
        private const val TAG = "ScreenService"
        /**
         * 拍摄延时
         */
        private const val DELAY = 300L
    }

    /**
     * 媒体工程
     */
    private var mMediaProjection: MediaProjection? = null
    /**
     * 虚拟化显示
     */
    private var mVirtualDisplay: VirtualDisplay? = null
    /**
     * 屏幕宽度
     */
    private var mWindowWidth = 720
    /**
     * 屏幕高度
     */
    private var mWindowHeight = 1080
    /**
     * 屏幕像素
     */
    private var mScreenDensity = 0
    /**
     * 图像读取者
     */
    private var mImageReader: ImageReader? = null
    /**
     * 悬浮按钮
     */
    private var mFab: View? = null
    /**
     * 图片监听
     */
    private var mPictureListener: IPictureListener? = null

    override fun onBind(intent: Intent): IBinder? = PictureBinder()

    override fun onCreate() {
        super.onCreate()
        // 创建悬浮按钮
        mFab = FloatView.addFloatView(applicationContext, View.OnClickListener {
            // 截屏
            screenShot()
        })
        // 创建虚拟化环境
        createVirtualEnvironment()
    }


    /**
     * 创建虚拟化环境
     */
    private fun createVirtualEnvironment() {
        initDisplay()
        // 创建图片读取这
        mImageReader = ImageReader.newInstance(mWindowWidth, mWindowHeight, PixelFormat.RGBA_8888, 2)

        Log.i(TAG, "prepared the virtual environment")
    }

    /**
     * 初始化显示数据
     */
    private fun initDisplay() {
        // 获取屏幕宽高
        val display = ScreenUtil.getDisplay(this)
        mWindowWidth = display.x
        mWindowHeight = display.y
        // 获取屏幕 DPI
        mScreenDensity = ScreenUtil.getDensityDpi(this)
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    fun startVirtual() {
        if (mMediaProjection != null) {
            Log.i(TAG, "want to display virtual")
            virtualDisplay()
        } else {
            Log.i(TAG, "mMediaProjection is null")
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun virtualDisplay() {
        mVirtualDisplay = mMediaProjection!!.createVirtualDisplay(
            "screen-mirror",
            mWindowWidth, mWindowHeight, mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            mImageReader!!.surface, null, null
        )
        Log.i(TAG, "virtual displayed")
    }

    /**
     * 停止并销毁媒体工程
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun tearDownMediaProjection() {
        if (mMediaProjection != null) {
            mMediaProjection!!.stop()
            mMediaProjection = null
        }
        L.d("mMediaProjection undefined")
    }

    /**
     * 停止虚拟化
     */
    private fun stopVirtual() {
        if (mVirtualDisplay == null) {
            return
        }
        mVirtualDisplay!!.release()
        mVirtualDisplay = null
        L.d("virtual display stopped")
    }

    override fun onDestroy() {
        tearDownMediaProjection()
        Log.i(TAG, "service destroy")
        removeFloatView()
        super.onDestroy()
    }

    /**
     * 设置媒体工具
     */
    fun setMediaProjection(mediaProjection: MediaProjection) {
        this.mMediaProjection = mediaProjection
    }

    /**
     * 截图
     */
    private fun screenShot() {
//        Toast.makeText(this, "截屏", Toast.LENGTH_SHORT).show()
        // 隐藏
        mFab?.visibility = View.GONE
        val handler = Handler(Looper.getMainLooper())
        handler.postDelayed({
            //startPermissionActivity virtual
            startVirtual()
        }, DELAY)
        handler.postDelayed({
            //capture the screen
            startCapture()
            mFab?.visibility = View.VISIBLE
        }, DELAY * 3)

        handler.postDelayed({
            // 停止虚拟化
            stopVirtual()
        }, DELAY * 2)
    }

    /**
     * 保存图片
     */
    private fun startCapture() {
        // 读取图片
        val image = mImageReader!!.acquireLatestImage()
        // 检测读取到的图片是否为空
        if (null != image) {
            // 获取 Bitmap
            val bitmap = FileUtil.getBitmap(image)
            bitmap?.let { mPictureListener?.onBitmap(it) }
            Log.i(TAG, "image data captured")
        } else {
            Log.i(TAG, "image is null")
        }
    }

    /**
     * 设置图片监听
     * @param listener 监听
     */
    fun setPictureListener(listener: IPictureListener) {
        this.mPictureListener = listener
    }

    /**
     * 移除悬浮按钮
     */
    private fun removeFloatView() {
        if (null != mFab) {
            FloatView.removeFloatView(this, mFab!!)
        }
    }

    /**
     * 图片绑定
     */
    inner class PictureBinder : Binder() {
        val service: ScreenService
            get() = this@ScreenService
    }

    /**
     * 图像监听
     */
    interface IPictureListener {
        /**
         * 获取 Bitmap
         * @param bitmap 图像数据
         */
        fun onBitmap(bitmap: Bitmap)
    }

}
